package com.xxkj.drugtraceability.ui.departdrug

import android.app.Application
import androidx.fragment.app.Fragment
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.xxhis.drugtraceability.base.BaseViewModel
import com.xxkj.drugtraceability.bean.*
import com.xxkj.drugtraceability.net.Result
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * author: zhoujingjin
 * created on: 2024/9/10 16:15
 * description:
 */
class DepartDrugCollectionViewModel(application: Application, private val repository: DepartDrugCollectionRepository):BaseViewModel(application) {
    var unDataList = MutableLiveData<MutableList<DepartDrugInfo>?>()
    var dataList = MutableLiveData<MutableList<DepartDrugInfo>?>()
    var baseUiModel = MutableLiveData<BaseUiModel<Boolean>>()
    //是否可以扫溯源码，如果处方码已经保存过追溯码，无论保存的多少，都不再让保存了。
    var canAdd = true
    var selectIndex = MutableLiveData(-1)
    var lastIndex = -1
    var barcode = ""
    var Prescriptionbarcode = ""
    var viewpagerIndex = MutableLiveData(0)
    var mFragmentList = mutableListOf<Fragment>()
    var departData = MutableLiveData<DepartDrug?>()
    fun getPrescriptionInfo(barcode:String){
        viewModelScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                baseUiModel.postValue(BaseUiModel(showLoading = true))
                val result = repository.queryPrescriptionInfoList(Gson().toJson(DepartDrugRequest("",barcode)))
                if (result is Result.Success){
                    if (result.data.data.bqdm.isNullOrEmpty()||result.data.data.drugInfoList.isNullOrEmpty()){
                        departData.postValue(null)
                        baseUiModel.postValue(BaseUiModel(showLoading = false,showError = "请检查领药单是否正确"))
                    }else{
                        departData.postValue(result.data.data)
                        Prescriptionbarcode = barcode
                        if(!result.data.data.drugInfoList.isNullOrEmpty()){
                            result.data.data.drugInfoList.forEach {
                                if (!it.drugTracInfos.isNullOrEmpty()){
                                    canAdd = false
                                    return@forEach
                                }
                            }
                            if (canAdd){
                                dataList.postValue(mutableListOf())
                                unDataList.postValue(result.data.data.drugInfoList as MutableList<DepartDrugInfo>?)
                            }else{
                                unDataList.postValue(mutableListOf())
                                dataList.postValue(result.data.data.drugInfoList as MutableList<DepartDrugInfo>?)
                            }
                        }else{

                        }
                        baseUiModel.postValue(BaseUiModel(showLoading = false))
                    }

                }else if (result is Result.Error){
                    baseUiModel.postValue(BaseUiModel(showLoading = false,showError = result.errorData?:result.exception.message))
                }
            }
        }
    }
    fun trugTracCodgIsGather(barcode:String){
        viewModelScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                baseUiModel.postValue(BaseUiModel(showLoading = true))
                this@DepartDrugCollectionViewModel.barcode = barcode
                val result = repository.trugTracCodgIsGather(Gson().toJson(TraceRequest(barcode,"")))
                if (result is Result.Success){
                    if (result.data.data.isGather){
                        if(result.data.data.drugDictInfo==null){
                            baseUiModel.postValue(BaseUiModel(showLoading = false,showError = "未找到与溯源码匹配的药品,请手动选中到待扫描的药品"))
                        }
                        else{
                            var indexTemp = -1
                            dataList.value?.forEach {
                                it.drugTracInfos?.forEach {drug->
                                    if (drug.drugTracCodg==barcode){
                                        baseUiModel.postValue(BaseUiModel(showLoading = false,showError = "该追溯码已在列表中，无需重复扫码"))
                                        return@withContext
                                    }
                                }
                            }
                            unDataList.value?.forEachIndexed  { index, drugInfoBean ->
                                result.data.data.drugDictInfo.forEach {resultDrugDictInfo->
                                    if (resultDrugDictInfo.drugCode==drugInfoBean.ydbh){
                                        indexTemp = index
                                        lastIndex = selectIndex.value?:-1
                                        selectIndex.postValue(index)
                                        baseUiModel.postValue(BaseUiModel(showLoading = false))
                                        return@withContext
                                    }
                                }
                            }
                            //选中的时候就算没有查到也要去往里面加
                            if (selectIndex.value!=-1){
                                selectIndex.postValue(selectIndex.value)
                                baseUiModel.postValue(BaseUiModel(showLoading = false))
                            }else{
                                if (indexTemp==-1){
                                    baseUiModel.postValue(BaseUiModel(showLoading = false,showError = "未找到与溯源码匹配的药品,请手动选中到待扫描的药品"))
                                }else{
                                    baseUiModel.postValue(BaseUiModel(showLoading = false))
                                }
                            }

                        }
                    }else{
                        baseUiModel.postValue(BaseUiModel(showLoading = false,showError = result.data.data.gatherMsg))
                    }

                }else if (result is Result.Error){
                    baseUiModel.postValue(BaseUiModel(showLoading = false,showError = result.errorData?:result.exception.message))
                }
            }
        }
    }

    /**
     * 保存数据
     */
    fun finishScanDrugCode(finishRequest: FinishDepartRequest){
        viewModelScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                baseUiModel.postValue(BaseUiModel(showLoading = true))
                val result = repository.finishScanDrugCode(GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(finishRequest))
                if (result is Result.Success){
                    baseUiModel.postValue(BaseUiModel(showLoading = false,showSuccess = true))
                    barcode = ""
                    Prescriptionbarcode = ""
                    departData.postValue(null)
                    Prescriptionbarcode = ""
                    lastIndex = -1
                    dataList.postValue(mutableListOf())
                    unDataList.postValue(mutableListOf())
                    canAdd = false
                }else if (result is Result.Error){
                    baseUiModel.postValue(BaseUiModel(showLoading = false,showError = result.errorData?:result.exception.message))
                }
            }
        }
    }
}